package aiku.numericalcontroloa.Controller;

import aiku.numericalcontroloa.Base.Exception.BizException;
import aiku.numericalcontroloa.Base.Utils.HttpStatus;
import aiku.numericalcontroloa.Base.Utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.tika.Tika;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

/**
 * @ClassName com.martialcollege.project.user.controller
 * @Description
 * @Author HuangWX
 * @Time 2023/10/20 11:39
 */
@RestController
@RequestMapping("/upload")
@Slf4j
public class UploadCont {

    @Value("${numericalControlOa.imagePath}")
    private String imagePath;

    @Value("${numericalControlOa.videoUploadDir}")
    private String VIDEO_UPLOAD_DIR;

    @Value("${numericalControlOa.fileBasePath}")
    private String fileBasePath;

    // jpg和png的魔数,webp的魔数为52494646
    private static final String[] EXCEL_MAGIC_NUMBERS = {
            "FFD8FF",
            "89504E47",
            "52494646"
    };

    // 限制图片文件大小为5MB
    private static final long IMAGE_MAX_FILE_SIZE = 5 * 1024 * 1024;

    // 限制视频文件大小为500MB
    private static final long VIDEO_MAX_FILE_SIZE = 500 * 1024 * 1024;

    /**
     * 上传图片
     * 
     * @param file 图片文件
     * @return 结果
     * @throws IOException IO异常
     */
    @PostMapping("/image")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {

        if (file.isEmpty()) {
            return new Result(HttpStatus.BAD_NO_PASS, "文件不能为空");
        }
        String originalFilename = file.getOriginalFilename();
        String extension = "." + FilenameUtils.getExtension(originalFilename);

        // 检查文件大小
        if (file.getSize() > IMAGE_MAX_FILE_SIZE) {
            return new Result(HttpStatus.BAD_NO_PASS, "图片大小超过5MB");
        }

        boolean isImage = false;
        byte[] magicBytes = new byte[8];
        InputStream inputStream = file.getInputStream();
        int bytesRead = IOUtils.read(inputStream, magicBytes);

        if (bytesRead >= 8) {
            StringBuilder stringBuilder = new StringBuilder();
            for (byte b : magicBytes) {
                stringBuilder.append(String.format("%02X", b));
            }
            String hexHeader = stringBuilder.toString();
            for (String magicNumber : EXCEL_MAGIC_NUMBERS) {
                if (hexHeader.startsWith(magicNumber)) {
                    isImage = true;
                }
            }
        }
        if (!isImage) {
            return new Result(HttpStatus.BAD_NO_PASS, "图片格式只能为png或者JPG");
        }
        String fileName = UUID.randomUUID() + extension;
        File directory = new File(imagePath);
        if (!directory.exists()) {
            directory.mkdirs();
        }
        file.transferTo(new File(imagePath + fileName));
        return new Result(HttpStatus.SUCCESS, "上传成功", fileName);
    }

    @PostMapping("/video")
    public Result uploadVideo(@RequestParam("file") MultipartFile file) throws IOException {
        File directory = new File(VIDEO_UPLOAD_DIR);
        if (!directory.exists()) {
            directory.mkdirs();
        }

        if (file.isEmpty()) {
            return new Result(HttpStatus.BAD_NO_PASS, "文件不能为空");
        }

        // 检查文件大小
        if (file.getSize() > VIDEO_MAX_FILE_SIZE) {
            return new Result(HttpStatus.BAD_NO_PASS, "视频文件不能超过500MB");
        }

        Tika tika = new Tika();
        String detectedType = tika.detect(file.getInputStream());

        // 获取文件的输入流
        InputStream inputStream = file.getInputStream();

        // 检查文件类型是否为视频
        if (detectedType != null && detectedType.startsWith("video/")) {
            // 进一步检查文件头信息，可以根据实际需求添加其他视频格式的标识符
            byte[] headerBytes = new byte[8];
            inputStream.read(headerBytes);
            Path uploadPath = Paths.get(VIDEO_UPLOAD_DIR);
            String originalFilename = file.getOriginalFilename();
            String fileExtension = "";
            if (originalFilename != null && originalFilename.contains(".")) {
                fileExtension = FilenameUtils.getExtension(originalFilename);
            }
            String fileName = UUID.randomUUID() + (fileExtension.isEmpty() ? "" : ("." + fileExtension));
            Path filePath = uploadPath.resolve(fileName);
            // 保存文件到指定路径
            try (InputStream inputStreamSave = file.getInputStream()) {
                Files.copy(inputStreamSave, filePath, StandardCopyOption.REPLACE_EXISTING);
                return new Result(HttpStatus.SUCCESS, "上传成功", fileName);
            } catch (IOException e) {
                // 适当处理异常
                log.error("文件上传失败", e);
                throw new BizException(HttpStatus.ERROR, "视频上传失败");
            }

        }

        return new Result(HttpStatus.BAD_NO_PASS, "视频格式只能为mp4,avi,isMpeg");

    }

    @Value("${numericalControlOa.urlword}")
    String urlword;
    @Value("${numericalControlOa.urlexcel}")
    String urlexcel;
    @Value("${numericalControlOa.urlppt}")
    String urlppt;
    @Value("${numericalControlOa.urlpdf}")
    String urlpdf;
    @Value("${numericalControlOa.urlweizhi}")
    String urlweizhi;

    @PostMapping("/file")
    public Result uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        String filePath = fileBasePath;
        switch (extension) {
            case "doc":
            case "docx":
                filePath += urlword;
                break;
            case "xls":
            case "xlsx":
                filePath += urlexcel;
                break;
            case "ppt":
            case "pptx":
                filePath += urlppt;
                break;
            case "pdf":
                filePath += urlpdf;
                break;
            // case "png":
            // case "JPG":
            // return upload(file);
            default:
                // filePath += urlweizhi;
                return new Result(HttpStatus.BAD_NO_PASS, "请选正确文件上传");
        }

        File File = new File(filePath);
        // 如果文件夹不存在则创建
        if (!File.exists() && !File.isDirectory()) {
            File.mkdirs();
        }

        String fileName = UUID.randomUUID() + "." + extension;
        Path targetLocation = Paths.get(filePath).toAbsolutePath().normalize().resolve(fileName);
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
        return new Result(HttpStatus.SUCCESS, "上传成功", fileName);
    }
}
